package com.yonyou.service.demo.service;

import com.yonyou.service.demo.Consts;
import com.yonyou.service.demo.util.Utils;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class TokenService {
    public String buildToken(String appId) throws Exception {
        String content = appId + "," + String.valueOf(new Date().getTime() + Consts.SERVICE_TIME_OUT);
        return Utils.encrypt(content, Consts.PUBLIC_KEY);
    }

    public boolean checkToken(String appId, String token) {
        try {
            String decrypt = Utils.decrypt(token, Consts.PRIVATE_KEY);
            String[] decContents = decrypt.split(",");
            if (decContents.length == 2) {
                System.out.printf("Token: %s\nAppid: %s\nTime: %s", decContents[0], appId, decContents[1]);
                if (decContents[0].equals(appId)) {
                    Long tokenTime = Long.valueOf(decContents[1]);
                    if (tokenTime > (new Date().getTime())) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
